/**
* Content script of Pixiv Novel Downloader Chrome Extension
* Author: cjls1 2015/05/20
*/

function cleanHTMLTag(str)
{
    str = str.replace(/<br>/ig, '\r\n');
    str = str.replace(/<\/p>/ig, '</p>\r\n');
    str = str.replace(/<\/?[^>]*>/g,'');
    str = str.replace(/&nbsp;/ig,'');
    str = str.replace(/&lt;/ig,'<');
    str = str.replace(/&gt;/ig,'>');
    str = str.replace(/&amp;/ig,'&');
    str = str.replace(/&quot;/ig,'"');
    str = str.replace(/&apos;/ig,'\'');
    return str;
}

var prefix = 'www.pixiv.net/novel/show.php?id=';

function startParseAndSave()
{
    var url = document.location.href;
    var pos = url.indexOf(prefix);
    if (pos < 0)
    {
        return null;
    }
	
    var id = url.substr(pos + prefix.length);
    pos = id.indexOf('#')
    if (pos >= 0)
    {
        id = id.substring(0, pos);
    }
		
    var title = document.title;
    pos = title.lastIndexOf('/');
    if (pos >= 0)
    {
        title = title.substring(0, pos);
    }
	
    var name = id + " - " + title;
	
    var novel = document.title;
    novel += '\r\n\r\n==============================================\r\n\r\n';
	
    var content = document.body.getElementsByClassName('novel-page');
    if (content.length == 0)
    {
        return null;
    }
    for (var i=0; i<content.length; i++) {
        novel += '\r\n[page ' + (i+1) + ']\r\n\r\n';
        src = cleanHTMLTag(content[i].innerHTML);
        novel += src;
        novel += '\r\n\r\n';
    }
	
    exportToFile(name, novel);
}

function exportToFile(name, txt) {
    var url = 'data:text/csv;charset=utf-8,' + encodeURI(txt);
	
    var downloadLink = document.createElement("a");
	
    downloadLink.href = url;
    downloadLink.download = name + ".txt";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request == "getClickedEl") {
	startParseAndSave();
        //sendResponse({value: "for test"});
    }
});

document.addEventListener("mousedown", function(event){
    if (event.button != 2) {
        return false;
    }

    var url = document.location.href;
    var pos = url.indexOf(prefix);
    if (pos < 0)
    {
	chrome.extension.sendMessage({
	    'message': 'updateContextMenu', 
	    'correcturl': false});
    }
    else
    {
        chrome.extension.sendMessage({
	    'message': 'updateContextMenu',
	    'correcturl': true});
    }
}, true);
